<?php
use app\we\sdk\Thinkwechat;
use app\we\sdk\Wechat;
use app\we\sdk\ErrCode;
use app\we\sdk\jssdk;
use app\we\sdk\wxauth;


// 从微信获取用户信息
// public function myinfo()
function weObj($appid)
 {
        
    $options = model('we/We')->info($appid);
    $weObj = new Thinkwechat($options);
    $weObj->options=$options;
   
   
    return $weObj;
}

function weErr($weObj,$res='')
{
    // TODO::可能要发送邮件，并且记录错误
    if (!$res) {
        $error=ErrCode::getErrText($weObj->errCode);
        mylog($error);
        return $error;
    }

    return;
}


// 从微信获取用户信息
// public function myinfo()
function getUserInfo($appid,$openid)
 {

    $weObj=weObj($appid);
    $fans=$weObj->getUserInfo($openid );
     
    weErr($weObj,$fans);
    
    if ($fans){
      $fans['appid']=$appid;
      $fans['aid']=$weObj->options['aid'];  
    } 
    
    return $fans;
}

/**
 * 发送客服消息
 * 可以直接发送一个机器人功能id
 * 可以原生数组方式发送
 * @return boolean true-成功，false-失败
 * @author $this <498944516@qq.com>
 */
function customMessage($to,$answer)
 {
    $fans=model('we/WeFans')->info($to);
    if (!is_array($answer)){ 
    //如果是机器人消息,带上必要的用户信息去获取机器人
    $data['fans']=$fans;
    $reply=model('Rob/RobAnswer')->infoByMap(['id'=>$answer],$data);
    $reply['touser']=$fans['openid'];
    $reply['msgtype']=$reply['type'];
    //将机器人返回格式化成客服消息内容
    switch ($reply['type']) {
         case 'text':
             $reply['text']=['content'=>$reply['message']];
             break;
        case 'news':
        //腾讯有病，这里键值和其他消息不一致，所以全部转小写
             foreach ($reply['message'] as $key => &$value) {
                $value=array_change_key_case($value);
             }
             $reply['news']=['articles'=>$reply['message']];
             break;
         
         default:
             # code...
             break;
     }
    }else{
       $reply=$answer;
       $reply['touser']=$fans['openid'];
    }
   
     $weObj=weObj($fans['appid']);
     $ret=$weObj->checkAuth();
     $res=$weObj->sendCustomMessage($reply); 
     $error=weErr($weObj,$res);

     //记录发送日志
     $message=[
     'aid'=>$fans['aid'],
     'appid'=>$fans['appid'],
     'nickname'=>$fans['nickname'],
     'ToUserName'=>$fans['openid'],
     'FromUserName'=>'customMessage',
     'CreateTime'=>time(),
     'MsgType'=>$reply['msgtype'],
     'status'=>0
     ];
    
     model('we/WeMessage')->saveMessage($message);
     return $error;
}


     /**
     * sendTemplateMessage  发送模板消息
     * @author:$this 498944516@qq.com
     * $reply=[
       template_id'=>'LsIc21raK3kWuX8j8hgBwJ-1cWn35PIdxgz2KMxgMPQ',
      'url'=>'http://baidu.com',
      'data'=>[
      'first'=>['value'=>'你好'],
      'keyword1'=>['value'=>'你好'],
      'remark'=>['value'=>'你好']
      ]
      ];
     */
 function templateMessage($to,$data)
    {
      
        $fans=model('we/WeFans')->info($to);
        $reply['touser'] = $fans['openid'];
        $reply['template_id']=$data['template_id'];
        $reply['url']=$data['url'];
        $reply['data']=$data['data'];
       
        $weObj=weObj($fans['appid']);
        $res=$weObj->checkAuth();
        $res=$weObj->sendTemplateMessage($reply); 
        weErr($weObj,$res);

        //记录发送日志
        $message=[
             'aid'=>$fans['aid'],
             'appid'=>$fans['appid'],
             'nickname'=>$fans['nickname'],
             'ToUserName'=>$fans['openid'],
             'FromUserName'=>'templateMessage',
             'CreateTime'=>time(),
             'MsgType'=>'templateMessage',
             'status'=>0
             ];
        
         model('we/WeMessage')->saveMessage($message);
         
        return true;
    }

    /**
     * sendGroupMassMessage  群发消息
     * @author:$this 498944516@qq.com
     * $reply=[
       filter'=>["is_to_all"=>False,  "group_id"=>"2" ],
        mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
     * text => array ( "content" => "hello")
     */
 function sendGroupMassMessage($appid,$reply)
    {
        
        $reply=[
        'filter'=>['is_to_all'=>true],
        "msgtype"=>"text",
        'text'=>['content'=>'hello wechat']
        ];

        $weObj=weObj($appid);
        $options=$weObj->options;
        $res=$weObj->checkAuth();
        $res=$weObj->sendGroupMassMessage($reply); 
        weErr($weObj,$res);

        //记录发送日志
        $message=[
             'aid'=>$options['aid'],
             'appid'=>$options['appid'],
             'nickname'=>'sendGroupMassMessage',
             'ToUserName'=>'sendGroupMassMessage',
             'FromUserName'=>'sendGroupMassMessage',
             'CreateTime'=>time(),
             'MsgType'=>'sendGroupMassMessage',
             'status'=>0
             ];
        
         model('we/WeMessage')->saveMessage($message);
         
        return true;
    }

     //生成二维码  getQRCode($appid,1);
    function getQRCode($appid,$type=0,$scene_id='',$expire=604800)
    {
        $weObj=weObj($appid);
        $res=$weObj->checkAuth();
        //如果不是scene_str 则自动获取id
        if ($type==0 or $type==1) $scene_id=model('WeSceneQrcode')->autoScene_id($appid,$type);
        mylog($scene_id.$type.$expire);
        $qrcode=$weObj->getQRCode($scene_id,$type,$expire);
        weErr($weObj,$qrcode);
        $qrcode['url']=$weObj->getQRUrl($qrcode['ticket']);
        weErr($weObj,$qrcode['url']);
        //创建短链接
        $qrcode['short_url'] = getShortUrl($appid,$qrcode['url']);
        
        //补充必要信息
        $qrcode['appid'] =$appid;
        $qrcode['qrcode_type'] =$type;
        if ($type==2){
            $qrcode['scene_str'] =$scene_id;
        }else{
            $qrcode['scene_id'] =$scene_id;
        }
        if ($type==0) $qrcode['expire'] =$expire;

      
        return $qrcode;
    }

    //创建短网址
    function getShortUrl($appid,$long)
    {
        $weObj=weObj($appid);
        $res=$weObj->checkAuth();
        
        $short=$weObj->getShortUrl($long);
        weErr($weObj,$short);
       
        return $short;
    }


     //同步菜单
    function sendMenu($appid,$my_menu)
    {
        
        $weObj=weObj($appid);
        $res=$weObj->checkAuth();
      
        if(isset($my_menu['matchrule'])){
        $res=$weObj->addconditionalMenu($my_menu);
        }else{
        $res=$weObj->createMenu($my_menu);
        }
        $error=weErr($weObj,$res);
       
        return $error;
    }

      //同步菜单
    function getMenu($appid)
    {
        $weObj=weObj($appid);
        $res=$weObj->checkAuth();
        
        $menu=$weObj->getMenu();
        $error=weErr($weObj,$menu);
     
       
        return $menu;
    }

      //同步菜单
    function getMedia($appid,$MediaId)
    { 
        $weObj=weObj($appid);
        $res=$weObj->checkAuth();
        
        $pic = $weObj->getMedia($MediaId);
        $error=weErr($weObj,$pic);
    
        return $pic;
    }

    //创建文件夹
    function createFolder($dirname){
         if (!file_exists($dirname)){   
         createFolder(dirname($dirname));     
         mkdir($dirname,0777); }
    }

    





